package com.biz.primus.ms.depot.dao.specfication;

import com.biz.primus.model.depot.vo.DepotQueryReqVo;
import com.biz.primus.ms.depot.dao.po.Depot;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author JKLiues
 * @date 2017/10/23
 */
public class DepotSpecification implements Specification<Depot> {

    private DepotQueryReqVo vo;

    public DepotSpecification(DepotQueryReqVo vo) {
        this.vo = vo;
    }

    @Override
    public Predicate toPredicate(Root<Depot> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotBlank(vo.getName())) {
            predicates.add(cb.like(root.get("name").as(String.class), "%" + vo.getName() + "%"));
        }
        if (StringUtils.isNotBlank(vo.getDepotCode())) {
            predicates.add(cb.equal(root.get("depotCode").as(String.class), vo.getDepotCode()));
        }
        if (vo.getDistrictId() != null) {
            predicates.add(cb.equal(root.get("districtId").as(Long.class), vo.getDistrictId()));
        } else if (vo.getCityId() != null) {
            predicates.add(cb.equal(root.get("cityId").as(Long.class), vo.getCityId()));
        } else if (vo.getProvinceId() != null) {
            predicates.add(cb.equal(root.get("provinceId").as(Long.class), vo.getProvinceId()));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
}
